package com.jaws.core.common.shard.util;

import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr;
import com.alibaba.druid.sql.ast.statement.SQLExprTableSource;
import com.alibaba.druid.sql.ast.statement.SQLSelect;
import com.alibaba.druid.sql.ast.statement.SQLSelectStatement;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitorAdapter;

/**
 * 替换sql table名称
 *
 * @author liangqm
 * @date 2018-05-11 14:40:17
 * @since v1.0.2
 */
public class TableNameModifier extends MySqlASTVisitorAdapter {
	private String tableName;
	private String newTableName;

	public TableNameModifier(String tableName, String newTableName) {
		this.tableName = tableName;
		this.newTableName = newTableName;
	}

	@Override
	public boolean visit(SQLSelectStatement astNode) {
		astNode.getSelect().accept(this);
		return false;
	}

	@Override
	public boolean visit(SQLSelect x) {
		x.getQuery().accept(this);
		return false;
	}

	@Override
	public boolean visit(SQLExprTableSource x) {
		x.getExpr().accept(this);
		return false;
	}

	@Override
	public boolean visit(SQLIdentifierExpr x) {
		if (x.getName().toLowerCase().trim().equals(tableName)) {
			x.setName(newTableName);
		}
		return false;
	}
}  